package com.echat.serviceapigateway.security.service.impl;

import com.echat.commonlib.exception.exc.ValidateFailedException;
import com.echat.serviceapigateway.security.mapper.AdminUserMapper;
import com.echat.serviceapigateway.security.model.admin.AdminUser;
import com.echat.serviceapigateway.security.service.AdminUserService;
import com.echat.serviceapigateway.security.tool.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

/**
 * Created by chenmohan on 2018/09/14
 *
 * @description
 */
@Service
public class AdminUserServiceImpl implements AdminUserService {

    @Autowired
    BCryptPasswordEncoder passwordEncoder;

    @Autowired
    AdminUserMapper adminUserMapper;

    @Override
    public AdminUser login(AdminUser user) {
        if (StringUtils.isEmpty(user.getUserName()) || StringUtils.isEmpty(user.getPassword())) {
            throw new ValidateFailedException("账号或密码不能为空");
        }
        //根据账号名查询账号
        AdminUser result = getAdminUserByUserName(user.getUserName());
        //是否存在该账号
        if (result == null) {
            throw new ValidateFailedException("账号不存在");
        }
        //验证该账号密码
        if (!passwordEncoder.matches(user.getPassword(), result.getPassword())) {
            throw new ValidateFailedException("密码错误");
        }

        //清除一些用户敏感信息返回前端
        result.setPassword(null);
        return result;
    }

    @Override
    public AdminUser getAdminUserByUserName(String userName) {
        Example example = new Example(AdminUser.class);
        example.createCriteria().andEqualTo("userName", userName);
        return adminUserMapper.selectOneByExample(example);
    }

}
